using Newtonsoft.Json;
using RuoVea.ExCache;

namespace RuoVea.OmiApi.User.Service;

/// <summary>
/// 系统缓存服务🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysCacheService : IApplicationService
{
    /// <summary>
    /// 
    /// </summary>
    public SysCacheService()
    {
    }
    /// <summary>
    /// 删除用户机构缓存
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="dbConfigId"></param>
    [NonAction]
    public void DeleteUserOrgCache(long userId, string dbConfigId)
    {
        // 删除用户机构集合缓存
        Remove($"{CacheConst.KeyUserOrg}{userId}");
        // 删除最大数据权限缓存
        Remove($"{CacheConst.KeyRoleMaxDataScope}{userId}");
        // 删除用户机构（数据范围）缓存——过滤器
        Remove($"db:{dbConfigId}:orgList:{userId}");
    }
    ///// <summary>
    ///// 申请分布式锁
    ///// </summary>
    ///// <param name="key">要锁定的key</param>
    ///// <param name="msTimeout">申请锁等待的时间，单位毫秒</param>
    ///// <param name="msExpire">锁过期时间，超过该时间没有主动是放则自动是放，必须整数秒，单位毫秒</param>
    ///// <param name="throwOnFailure">失败时是否抛出异常,如不抛出异常，可通过判断返回null得知申请锁失败</param>
    ///// <returns></returns>
    //[DisplayName("申请分布式锁")]
    //public IDisposable? BeginCacheLock(string key, int msTimeout = 500, int msExpire = 10000, bool throwOnFailure = true)
    //{
    //    try
    //    {
    //        return RuoVea.ExCache.CacheFactery.Cache.AcquireLock(key, msTimeout, msExpire, throwOnFailure);
    //    }
    //    catch
    //    {
    //        return null;
    //    }
    //}

    ///// <summary>
    ///// 获取缓存键名集合 🔹
    ///// </summary>
    ///// <returns></returns>
    //[DisplayName("获取缓存键名集合")]
    //public List<string> GetKeyList()
    //{
    //    return CacheFactery.Cache.Read()();
    //}

    /// <summary>
    /// 增加缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    [NonAction]
    public bool Set(string key, object value)
    {
        if (string.IsNullOrWhiteSpace(key)) return false;
        return CacheFactery.Cache.Write($"{key}", value);
    }

    /// <summary>
    /// 增加缓存并设置过期时间
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expire"></param>
    /// <returns></returns>
    [NonAction]
    public bool Set(string key, object value, TimeSpan expire)
    {
        if (string.IsNullOrWhiteSpace(key)) return false;
        return CacheFactery.Cache.Write($"{key}", value, expire);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TR"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="del"></param>
    /// <param name="expiry"></param>
    /// <returns></returns>
    public async Task<TR> AdGetAsync<TR>(string cacheName, Func<Task<TR>> del, TimeSpan? expiry = default) where TR : class
    {
        return await AdGetAsync<TR>(cacheName, del, new object[] { }, expiry);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TR"></typeparam>
    /// <typeparam name="T1"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="del"></param>
    /// <param name="t1"></param>
    /// <param name="expiry"></param>
    /// <returns></returns>
    public async Task<TR> AdGetAsync<TR, T1>(string cacheName, Func<T1, Task<TR>> del, T1 t1, TimeSpan? expiry = default) where TR : class
    {
        return await AdGetAsync<TR>(cacheName, del, new object[] { t1 }, expiry);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TR"></typeparam>
    /// <typeparam name="T1"></typeparam>
    /// <typeparam name="T2"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="del"></param>
    /// <param name="t1"></param>
    /// <param name="t2"></param>
    /// <param name="expiry"></param>
    /// <returns></returns>
    public async Task<TR> AdGetAsync<TR, T1, T2>(string cacheName, Func<T1, T2, Task<TR>> del, T1 t1, T2 t2, TimeSpan? expiry = default) where TR : class
    {
        return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2 }, expiry);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TR"></typeparam>
    /// <typeparam name="T1"></typeparam>
    /// <typeparam name="T2"></typeparam>
    /// <typeparam name="T3"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="del"></param>
    /// <param name="t1"></param>
    /// <param name="t2"></param>
    /// <param name="t3"></param>
    /// <param name="expiry"></param>
    /// <returns></returns>
    public async Task<TR> AdGetAsync<TR, T1, T2, T3>(string cacheName, Func<T1, T2, T3, Task<TR>> del, T1 t1, T2 t2, T3 t3, TimeSpan? expiry = default) where TR : class
    {
        return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2, t3 }, expiry);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="del"></param>
    /// <param name="obs"></param>
    /// <param name="expiry"></param>
    /// <returns></returns>
    private async Task<T> AdGetAsync<T>(string cacheName, Delegate del, object[] obs, TimeSpan? expiry) where T : class
    {
        return await CacheFactery.Cache.ReadAsync<T>(cacheName);
        //var key = Key(cacheName, obs);
        //// 使用分布式锁
        //using (_cacheProvider.Cache.AcquireLock($@"lock:AdGetAsync:{cacheName}", 1000))
        //{
        //    var value = Get<T>(key);
        //    value ??= await ((dynamic)del).DynamicInvokeAsync(obs);
        //    Set(key, value);
        //    return value;
        //}
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="t1"></param>
    /// <returns></returns>
    public T Get<T>(string cacheName, object t1)
    {
        return Get<T>(cacheName, new object[] { t1 });
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="t1"></param>
    /// <param name="t2"></param>
    /// <returns></returns>
    public T Get<T>(string cacheName, object t1, object t2)
    {
        return Get<T>(cacheName, new object[] { t1, t2 });
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="t1"></param>
    /// <param name="t2"></param>
    /// <param name="t3"></param>
    /// <returns></returns>
    public T Get<T>(string cacheName, object t1, object t2, object t3)
    {
        return Get<T>(cacheName, new object[] { t1, t2, t3 });
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="cacheName"></param>
    /// <param name="obs"></param>
    /// <returns></returns>
    private T Get<T>(string cacheName, object[] obs)
    {
        var key = cacheName + ":" + obs.Aggregate(string.Empty, (current, o) => current + $"<{o}>");
        return Get<T>(key);
    }

    //private static string Key(string cacheName, object[] obs)
    //{
    //    foreach (var obj in obs)
    //    {
    //        if (obj is TimeSpan)
    //        {
    //            throw new Exception("缓存参数类型不能能是:TimeSpan类型");
    //        }
    //    }
    //    StringBuilder sb = new StringBuilder(cacheName + ":");
    //    foreach (var a in obs)
    //    {
    //        sb.Append($@"<{KeySingle(a)}>");
    //    }
    //    return sb.ToString();
    //}
    /// <summary>
    /// 
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public static string KeySingle(object t)
    {
        if (t.GetType().IsClass && !t.GetType().IsPrimitive)
        {
            return JsonConvert.SerializeObject(t);
        }
        return t?.ToString();
    }

    ///// <summary>
    ///// 获取缓存的剩余生存时间
    ///// </summary>
    ///// <param name="key"></param>
    ///// <returns></returns>
    //[NonAction]
    //public TimeSpan GetExpire(string key)
    //{
    //    return _cacheProvider.Cache.GetExpire(key);
    //}

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    [NonAction]
    public T Get<T>(string key)
    {
        return CacheFactery.Cache.Read<T>($"{key}");
    }

    /// <summary>
    /// 删除缓存 🔹
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    [HttpDelete("Delete")] 
    [DisplayName("删除缓存")]
    public long Remove(string key)
    {
        return CacheFactery.Cache.Del($"{key}");
    }

    /// <summary>
    /// 清空所有缓存 🔹
    /// </summary>
    /// <returns></returns>
    [DisplayName("清空所有缓存")]
    [HttpDelete("Clear")]
    public async Task Clear(string profix = "RuoVea*")
    {
        await CacheFactery.Cache.DelByPrefixAsync(profix);
    }

    /// <summary>
    /// 检查缓存是否存在
    /// </summary>
    /// <param name="key">键</param>
    /// <returns></returns>
    [NonAction]
    public bool ExistKey(string key)
    {
        return CacheFactery.Cache.Exists($"{key}");
    }

    /// <summary>
    /// 根据键名前缀删除缓存 🔹
    /// </summary>
    /// <param name="prefixKey">键名前缀</param>
    /// <returns></returns>
    [HttpDelete("DeleteByPreKey")]
    [DisplayName("根据键名前缀删除缓存")]
    public async Task<long> RemoveByPrefixKey(string prefixKey)
    {
        return await CacheFactery.Cache.DelByPrefixAsync(prefixKey);
    }

    /// <summary>
    /// 根据键名前缀获取键名集合 🔹
    /// </summary>
    /// <param name="prefixKey">键名前缀</param>
    /// <returns></returns>
    [DisplayName("根据键名前缀获取键名集合")]
    public List<string> GetKeysByPrefixKey(string prefixKey)
    {
        return CacheFactery.Cache.Read<List<string>>(prefixKey);
    }

    /// <summary>
    /// 获取缓存值 🔹
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    [DisplayName("获取缓存值")]
    public object GetValue(string key)
    {
        //// 若Key经过URL编码则进行解码
        //if (Regex.IsMatch(key, @"%[0-9a-fA-F]{2}"))
        //    key = HttpUtility.UrlDecode(key);

        //return _cacheProvider.Cache == Cache.Default
        //    ? _cacheProvider.Cache.Get<object>($"{key}")
        //    : _cacheProvider.Cache.Get<string>($"{key}");
        return CacheFactery.Cache.Read<object>(key);
    }

    ///// <summary>
    ///// 获取或添加缓存（在数据不存在时执行委托请求数据）
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="callback"></param>
    ///// <param name="expire">过期时间，单位秒</param>
    ///// <returns></returns>
    //[NonAction]
    //public T GetOrAdd<T>(string key, Func<string, T> callback, int expire = -1)
    //{
    //    if (string.IsNullOrWhiteSpace(key)) return default;
    //    return _cacheProvider.Cache.GetOrAdd($"{key}", callback, expire);
    //}

    ///// <summary>
    ///// Hash匹配
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <returns></returns>
    //[NonAction]
    //public IDictionary<String, T> GetHashMap<T>(string key)
    //{
    //    return _cacheProvider.Cache.GetDictionary<T>(key);
    //}

    ///// <summary>
    ///// 批量添加HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="dic"></param>
    ///// <returns></returns>
    //[NonAction]
    //public bool HashSet<T>(string key, Dictionary<string, T> dic)
    //{
    //    var hash = GetHashMap<T>(key);
    //    foreach (var v in dic)
    //    {
    //        hash.Add(v);
    //    }
    //    return true;
    //}

    ///// <summary>
    ///// 添加一条HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="hashKey"></param>
    ///// <param name="value"></param>
    //[NonAction]
    //public void HashAdd<T>(string key, string hashKey, T value)
    //{
    //    var hash = GetHashMap<T>(key);
    //    hash.Add(hashKey, value);
    //}

    ///// <summary>
    ///// 获取多条HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="fields"></param>
    ///// <returns></returns>
    //[NonAction]
    //public List<T> HashGet<T>(string key, params string[] fields)
    //{
    //    var hash = GetHashMap<T>(key);
    //    return hash.Where(t => fields.Any(c => t.Key == c)).Select(t => t.Value).ToList();
    //}

    ///// <summary>
    ///// 获取一条HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="field"></param>
    ///// <returns></returns>
    //[NonAction]
    //public T HashGetOne<T>(string key, string field)
    //{
    //    var hash = GetHashMap<T>(key);
    //    var value = hash.GetValue(field);
    //    if (value == null)
    //    {
    //        return default(T);
    //    }
    //    return (T)hash.GetValue(field);
    //}

    ///// <summary>
    ///// 根据KEY获取所有HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <returns></returns>
    //[NonAction]
    //public IDictionary<string, T> HashGetAll<T>(string key)
    //{
    //    var hash = GetHashMap<T>(key);
    //    return hash;
    //}

    ///// <summary>
    ///// 删除HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="fields"></param>
    ///// <returns></returns>
    //[NonAction]
    //public int HashDel<T>(string key, params string[] fields)
    //{
    //    var hash = GetHashMap<T>(key);
    //    fields.ToList().ForEach(t => hash.Remove(t));
    //    return fields.Length;
    //}

    ///// <summary>
    ///// 搜索HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="searchModel"></param>
    ///// <returns></returns>
    //[NonAction]
    //public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
    //{
    //    var hash = GetHashMap<T>(key);
    //    return hash.Search(searchModel).ToList();
    //}

    ///// <summary>
    ///// 搜索HASH
    ///// </summary>
    ///// <typeparam name="T"></typeparam>
    ///// <param name="key"></param>
    ///// <param name="pattern"></param>
    ///// <param name="count"></param>
    ///// <returns></returns>
    //[NonAction]
    //public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
    //{
    //    var hash = GetHashMap<T>(key);
    //    return hash.Search(pattern, count).ToList();
    //}
}